# -*- coding: utf-8 -*-
# Created by: Dagoose


from selenium import webdriver
import time
from read import *




def run():
    global driver, userinfo
    pre()
    username = password = ''
    userinfo = userInfo()
    loginState = input("使用登录方式(输入1或2) ：")
    while True:
        try:
            if loginState == "1":
                print("需要输入OA登录账号和密码！")
                if not userinfo.username and not userinfo.password:
                    username = input('请输入账号:')
                    password = input('请输入密码:')
                    userinfo.userLogin(username, password)
                elif not userinfo.username and userinfo.password:
                    username = input('请输入账号:')
                    password = userinfo.password
                    userinfo.userLogin(username, password)
                elif not userinfo.username and userinfo.password:
                    username = userinfo.username
                    password = input('请输入密码:')
                    userinfo.userLogin(username, password)
                else:
                    username = userinfo.username
                    password = userinfo.password
                break
            elif loginState == "2":
                break
        except:
            loginState = input("输入1或2：")

    print(f"当前地址：{userinfo.address()}")
    if userinfo.isFirst:
        alterState = input("第一次使用是否更改默认地址(是/否)：")
        while True:
            try:
                if alterState == "是":
                    alterAddress()
                    break
                elif alterState == "否":
                    break
            except:
                alterState = input("请填是或否：")
        userinfo.alter(isFirst=False)
    driver=webdriver.Chrome(executable_path=r'.\chromedriver.exe')
    login(loginState,username,password)





def login(loginState="",username="", password=""):
    # 进入登录页
    driver.get('https://oa-443.v.hbfu.edu.cn/datafill/collect/usertask')
    # 选择登录界面
    if loginState == "1":
    # 1.账户-密码-登录
        while True:
            try:
                if driver.find_elements_by_tag_name("input"):
                    user = driver.find_elements_by_tag_name("input")
                    print("登录页面加载完成")
                    break
            except:
                print("登录页面正在加载中")
        user[0].send_keys(username)
        user[1].send_keys(password)
        driver.find_element_by_class_name('button-margin').click()
        print("登录按钮点击成功 ")
    # 2.通过手机扫描二维码
    # time.sleep(3)
    selectInfo()


def selectInfo(sentTime="2020-12-31 00:00.00"):
    """选择需要填报的日期"""
    while True:
        # 找到当前第一条 未填写数据
        print("正在加载选择填报页面")
        while True:
            try:
                if driver.find_elements_by_class_name(
                        "ant-table-column-has-sorters"):
                    lastInfo = driver.find_elements_by_class_name(
                        "ant-table-column-has-sorters")[1]
                    print("加载选择填报页面成功")
                    break
            except:
                pass

        # 判断是否应该填写
        # print(lastInfo.text)
        aimTime = lastInfo.text
        if aimTime < sentTime:
            print("今年的疫情信息已经填完！感谢使用。")
            return
        else:
            # 勾选框 选中
            print("正在选中勾选框")
            # while True:
            #     try:
            #         if driver.find_element_by_xpath('//input[@type="radio"]'):
            #             driver.find_element_by_xpath('//input[@type="radio"]').click()
            #             print("勾选框选中成功")
            #             break
            #     except:
            #         pass
            driver.find_element_by_xpath('//input[@type="radio"]').click()
            print("勾选框选中成功")
            # 填写按钮点击
            while True:
                if driver.find_elements_by_class_name("ant-btn-primary")[1]:
                    driver.find_elements_by_class_name("ant-btn-primary")[1].click()
                    print("填写按钮点击成功")
                    time.sleep(1)
                    print(f"开始填写日期为 {aimTime} 的数据")
                    fillInfo()  # 填写开始
                    print(f"日期为 {aimTime} 的表单填写完成")
                    break



# def fillInfo(province="河北省", city="保定市", district="莲池区", township="韩庄乡", detail="河北金融学院"):
def fillInfo():
    """"自动填写疫情表单"""
    # 寻找地址窗口
    while True:
        try:
            if driver.find_element_by_class_name("ant-cascader-picker-show-search"):
                print("地址窗口找到了")
                driver.find_element_by_class_name("ant-cascader-picker-show-search").click()
                print("地址窗口点击成功")
                break
        except:
            print("地址窗口正在找寻找中")

    # 填写地址
    print("开始进行地址填写")
    # fillADress(province)
    # fillADress(city)
    # fillADress(district)
    # fillADress(township)
    # driver.find_element_by_xpath("//input[contains(@placeholder,'请输入详细地址')]").send_keys(detail)

    fillADress(userinfo.province, 1)
    fillADress(userinfo.city, 2)
    fillADress(userinfo.district, 3)
    fillADress(userinfo.township, 4)
    driver.find_element_by_xpath("//input[contains(@placeholder,'请输入详细地址')]").send_keys(userinfo.detail)
    print("地址填写完成")

    print("开始进行其他信息填写")
    for i in range(3):
        driver.find_elements_by_class_name("ant-select-enabled")[i].click()
        driver.find_elements_by_class_name("ant-select-dropdown-menu-item")[3 * i + 1].click()
    print("其他信息填写完成")
    print("信息填写完成")

    driver.find_element_by_css_selector(".ant-btn.ant-btn-primary.ant-btn-block").click()
    print("提交成功")
    time.sleep(1)
    driver.find_element_by_xpath('//*[@class="ant-modal-confirm-btns"]/button').click()
    time.sleep(2)
    return

def fillADress(address, num):
    while True:
        try:
            if driver.find_element_by_xpath(f"//li[contains(@title,'{address}')]"):
                button = driver.find_element_by_xpath(f"//li[contains(@title,'{address}')]")
                driver.execute_script("arguments[0].click();", button)
                # driver.find_element_by_xpath("//*[contains(@title,'%s')]" % address).click()
                return
        except:
            print(f"信息 “{address}” 有问题")
            address = input("请重新输入：")
            if num == 1:
                userinfo.alter(province=address)
            elif num == 2:
                userinfo.alter(city=address)
            elif num == 3:
                userinfo.alter(district=address)
            elif num == 4:
                userinfo.alter(township=address)
            else:
                print("错误异常")


def alterAddress():
    """更改地址"""
    province = input('请输入省/市（如河北/北京）:')
    city = "市辖区" if (province in "天津北京上海重庆") else input('请输入城市 (如保定）:')
    district = input('请输入区/县（如莲池区/安县）:')
    township = input('请输入乡/镇/街道（如韩庄乡/安县）:')
    detail = input('请输入详细地址（如河北金融学院）:')
    userinfo.alter(province=province, city=city, district=district, township=township, detail=detail, isFirst=False)


if __name__ == '__main__':
    run()
